package cn.outsourcing.supermarket.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;

/**
 * 条件构造器
 *
 * @author gzkemays
 * @since 2021/10/18 14:05
 */
public class WrapperUtils<T> {
  private static final String DELETE_KEY = "isDelete";
  private static final String HUMP_TO_DELETE_KEY = "is_delete";

  public static <T> WrapperBuilder<T> builder() {
    return new WrapperBuilder<>();
  }

  public static class WrapperBuilder<T> {
    Class<?> cz;
    T target;

    /**
     * 指定实体类 - class
     *
     * @param cz 目标实体类
     * @return 含参工具
     */
    public WrapperBuilder<T> targetClazz(Class<?> cz) {
      this.cz = cz;
      return this;
    }

    /**
     * 指定实体类
     *
     * @param target 目标实体类
     * @return 含参工具
     */
    public WrapperBuilder<T> targetEntity(T target) {
      this.cz = target.getClass();
      this.target = target;
      return this;
    }

    public <E> QueryWrapper<T> isNotDelete(Class<?> cz, boolean hump) {
      QueryWrapper<T> queryWrapper = new QueryWrapper<>();
      Field isDelete = null;
      try {
        isDelete = cz.getDeclaredField(DELETE_KEY);
      } catch (NoSuchFieldException e) {
        try {
          isDelete = cz.getDeclaredField(HUMP_TO_DELETE_KEY);
        } catch (NoSuchFieldException ex) {
          ex.printStackTrace();
        }
        e.printStackTrace();
      }
      if (isDelete != null) {
        return hump ? queryWrapper.eq(HUMP_TO_DELETE_KEY, 0) : queryWrapper.eq(DELETE_KEY, 0);
      }
      throw new IllegalArgumentException("无 delete 参数");
    }

    /**
     * 全字段映射 eq
     *
     * @param entity entity 对象
     * @param <E> entity 数据类型
     * @return mp 条件构造器
     */
    public <E> QueryWrapper<T> allEqByEntity(E entity) {
      QueryWrapper<T> queryWrapper = new QueryWrapper<>();
      Class<?> clazz = entity.getClass();
      Field[] currentFields = clazz.getDeclaredFields();
      Field[] targetFields;
      if (target == null) {
        targetFields = cz.getDeclaredFields();
      } else {
        targetFields = target.getClass().getDeclaredFields();
      }
      for (Field currentField : currentFields) {
        currentField.setAccessible(true);
        String fieldName = currentField.getName();
        for (Field targetField : targetFields) {
          String targetFieldName = targetField.getName();
          try {
            if (targetFieldName.equals(fieldName) && currentField.get(entity) != null) {
              queryWrapper.eq(StrUtils.humpToLine(targetFieldName), currentField.get(entity));
            }
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
        }
      }
      return queryWrapper;
    }
  }
}
